package cn.ranko.site.action;

import cn.ranko.bean.easyui.TreeNode;
import cn.ranko.site.model.SysUsers;
import cn.ranko.site.realm.UserRealm;
import cn.ranko.site.service.SysMenusService;
import cn.ranko.site.service.SysPermissionsService;
import cn.ranko.site.service.SysUsersService;
import cn.ranko.utils.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by ZJ08 on 2016/7/18.
 */
@Controller
@RequestMapping("/site-default")
public class SysDefaultAction {

    @Autowired
    UserRealm userRealm;

    @Autowired
    SysUsersService sysUsersService;

    @Autowired
    SysPermissionsService sysPermissionsService;

    @Autowired
    SysMenusService sysMenusService;


    /**
     * 用户验证
     *
     */
    @RequestMapping(value = "check.action",method = RequestMethod.POST)
    public String check(SysUsers users) {

        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(users.getUsername(),users.getPassword());
        token.setRememberMe(true);
        try {
            user.login(token);

            return "redirect:/index.html";
        }catch (AuthenticationException e) {
            token.clear();
            return "redirect:/login.html";
        }
    }

    @RequestMapping(value = "getUser.action",method = RequestMethod.GET)
    @ResponseBody
    public String getUser(){
        return  SecurityUtils.getSubject().getPrincipal().toString();
    }


    /**
     * 后台默认页面
     * @return
     */
    @RequestMapping(value = "portal.action",method = RequestMethod.GET)
    public String portal(){
        return "site/default/portal";
    }

    /**
     * 获取菜单
     *
     * @return
     */
    @RequestMapping(value = "getmenu.action",method = RequestMethod.GET)
    @ResponseBody
    public List<TreeNode> getmenu(){
        Subject currentUser = SecurityUtils.getSubject();
        String principals = currentUser.getPrincipals().toString();
        SysUsers sysUsers = sysUsersService.findByUsername(principals);
        Long userId = sysUsers.getId();

        List<TreeNode> treeNodes = sysMenusService.getMenusByUserId(userId);

        return treeNodes;
    }

    /**
     * 退出登入操作
     *
     * @return
     */
    @RequestMapping(value = "logout.action",method = RequestMethod.GET)
    public String logout(){
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "redirect:../";
    }


}
